<template>
  <div class="migrations-container">
    <div class="header">
      <div class="header-left">
        <h2>迁移任务管理</h2>
        <span class="task-count">共 {{ taskList.length }} 个任务</span>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="el-icon-plus" @click="showCreateDialog">
          创建迁移任务
        </el-button>
      </div>
    </div>

    <!-- 过滤器 -->
    <el-card class="filter-card">
      <div slot="header">
        <span>筛选条件</span>
      </div>
      <el-form :model="filterForm" label-width="80px" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="任务名称">
              <el-input 
                v-model="filterForm.taskName" 
                placeholder="请输入任务名称"
                clearable
                @clear="handleFilter"
                @keyup.enter.native="handleFilter"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务状态">
              <el-select 
                v-model="filterForm.status" 
                placeholder="请选择状态" 
                clearable
                @clear="handleFilter"
                @change="handleFilter"
              >
                <el-option label="待执行" value="PENDING"></el-option>
                <el-option label="运行中" value="RUNNING"></el-option>
                <el-option label="已完成" value="COMPLETED"></el-option>
                <el-option label="失败" value="FAILED"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="迁移类型">
              <el-select 
                v-model="filterForm.migrationType" 
                placeholder="请选择类型" 
                clearable
                @clear="handleFilter"
                @change="handleFilter"
              >
                <el-option label="全系统" value="FULL_SYSTEM"></el-option>
                <el-option label="部分目录" value="PARTIAL_DIRECTORY"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 任务表格 -->
    <el-table 
      :data="paginatedTasks" 
      v-loading="loading" 
      element-loading-text="加载中..."
      class="migrations-table"
      stripe
    >
      <el-table-column prop="taskName" label="任务名称" min-width="150"></el-table-column>
      <el-table-column prop="migrationType" label="迁移类型" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.migrationType === 'FULL_SYSTEM' ? 'primary' : 'success'">
            {{ scope.row.migrationType === 'FULL_SYSTEM' ? '全系统' : '部分目录' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sourceServerName" label="源服务器" min-width="120"></el-table-column>
      <el-table-column prop="targetServerName" label="目标服务器" min-width="120"></el-table-column>
      <el-table-column prop="sourcePath" label="源路径" min-width="150"></el-table-column>
      <el-table-column prop="targetPath" label="目标路径" min-width="150"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="progress" label="进度" width="120">
        <template slot-scope="scope">
          <el-progress
            :percentage="scope.row.progress"
            :status="getProgressStatus(scope.row.status)"
            :stroke-width="12"
            text-inside
          ></el-progress>
          <div class="progress-text">{{ scope.row.progress }}%</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="primary" 
            @click="showDetails(scope.row)"
          >
            详情
          </el-button>
          <el-button 
            size="mini" 
            type="success" 
            @click.stop="executeTask(scope.row)" 
            :disabled="scope.row.status !== 'PENDING' && scope.row.status !== 'FAILED'"
            v-if="scope.row.status === 'PENDING' || scope.row.status === 'FAILED'"
          >
            执行
          </el-button>
          <el-button 
            size="mini" 
            type="warning" 
            @click.stop="pauseTask(scope.row)" 
            :disabled="scope.row.status !== 'RUNNING'"
            v-if="scope.row.status === 'RUNNING'"
          >
            暂停
          </el-button>
          <el-button 
            size="mini" 
            type="success" 
            @click.stop="resumeTask(scope.row)" 
            :disabled="scope.row.status !== 'PAUSED'"
            v-if="scope.row.status === 'PAUSED'"
          >
            恢复
          </el-button>
          <el-button 
            size="mini" 
            type="danger" 
            @click.stop="stopTask(scope.row)" 
            :disabled="scope.row.status !== 'RUNNING' && scope.row.status !== 'PAUSED'"
            v-if="scope.row.status === 'RUNNING' || scope.row.status === 'PAUSED'"
          >
            停止
          </el-button>
          <el-button 
            size="mini" 
            type="warning" 
            @click.stop="reExecuteTask(scope.row)" 
            v-if="scope.row.status === 'COMPLETED' || scope.row.status === 'FAILED' || scope.row.status === 'STOPPED'"
          >
            再次执行
          </el-button>
          <el-button 
            size="mini" 
            type="danger" 
            @click.stop="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredTasks.length"
      >
      </el-pagination>
    </div>

    <!-- 创建/编辑任务对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      class="migration-dialog"
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="taskForm" 
        :rules="taskFormRules" 
        ref="taskForm" 
        label-width="120px" 
        class="migration-form"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="taskForm.taskName" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        
        <el-form-item label="迁移类型" prop="migrationType">
          <el-radio-group v-model="taskForm.migrationType" @change="handleMigrationTypeChange">
            <el-radio label="PARTIAL_DIRECTORY">部分目录迁移</el-radio>
            <el-radio label="FULL_SYSTEM">全系统迁移</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="源服务器" prop="sourceServerId">
              <el-select 
                v-model="taskForm.sourceServerId" 
                placeholder="请选择源服务器" 
                @change="handleSourceServerChange"
                filterable
              >
                <el-option
                  v-for="server in serverList"
                  :key="server.id"
                  :label="server.name + ' (' + server.hostname + ':' + server.port + ')'"
                  :value="server.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标服务器" prop="targetServerId">
              <el-select 
                v-model="taskForm.targetServerId" 
                placeholder="请选择目标服务器"
                @change="handleTargetServerChange"
                filterable
              >
                <el-option
                  v-for="server in serverList"
                  :key="server.id"
                  :label="server.name + ' (' + server.hostname + ':' + server.port + ')'"
                  :value="server.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 磁盘选择（仅全系统迁移时显示） -->
        <el-form-item v-if="taskForm.migrationType === 'FULL_SYSTEM' && diskList.length > 0">
          <el-alert
            title="请选择要迁移的磁盘（可多选）"
            type="info"
            show-icon
            :closable="false"
            style="margin-bottom: 10px;"
          >
          </el-alert>
          <el-checkbox-group v-model="selectedDisks">
            <el-checkbox 
              v-for="disk in diskList" 
              :key="disk.name" 
              :label="disk.name"
            >
              {{ disk.name }} ({{ disk.size }})
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item v-if="taskForm.migrationType === 'FULL_SYSTEM' && diskLoadError">
          <el-alert
            :title="diskLoadError"
            type="error"
            show-icon
            :closable="false"
            style="margin-top: 10px;"
          >
          </el-alert>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="源路径" prop="sourcePath" v-if="taskForm.migrationType === 'PARTIAL_DIRECTORY'">
              <el-input v-model="taskForm.sourcePath" placeholder="请输入源路径">
                <el-button 
                  slot="append" 
                  icon="el-icon-folder" 
                  @click="showSourcePathSelector"
                  :disabled="!taskForm.sourceServerId"
                >
                  选择
                </el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标路径" prop="targetPath" v-if="taskForm.migrationType === 'PARTIAL_DIRECTORY'">
              <el-input v-model="taskForm.targetPath" placeholder="请输入目标路径">
                <el-button 
                  slot="append" 
                  icon="el-icon-folder" 
                  @click="showTargetPathSelector"
                  :disabled="!taskForm.targetServerId"
                >
                  选择
                </el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item v-if="taskForm.migrationType === 'FULL_SYSTEM'">
          <el-alert
            title="全系统迁移将迁移整个系统盘，无需指定源路径和目标路径"
            type="info"
            show-icon
            :closable="false">
          </el-alert>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="taskForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入任务描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 源路径选择对话框 -->
    <el-dialog
      title="选择源路径"
      :visible.sync="pathSelectorVisible"
      width="600px"
      class="path-selector-dialog"
    >
      <div v-loading="pathLoading">
        <el-alert
          :title="'当前服务器: ' + (currentServer ? currentServer.name : '')"
          type="info"
          show-icon
          :closable="false"
          style="margin-bottom: 15px;"
        >
        </el-alert>
        
        <el-breadcrumb separator="/" style="margin-bottom: 15px;">
          <el-breadcrumb-item 
            v-for="(path, index) in breadcrumbPaths" 
            :key="index"
            @click.native="navigateToPath(path.path)"
            style="cursor: pointer;"
          >
            {{ path.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
        
        <el-table 
          :data="directoryList" 
          style="width: 100%"
          max-height="400"
          @row-click="handleDirectoryClick"
        >
          <el-table-column prop="name" label="目录名称">
            <template slot-scope="scope">
              <i class="el-icon-folder" style="color: #409EFF; margin-right: 5px;"></i>
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column prop="path" label="完整路径" show-overflow-tooltip></el-table-column>
        </el-table>
        
        <div style="margin-top: 15px; text-align: right;">
          <el-button @click="pathSelectorVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPathSelection">确定选择</el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 任务详情对话框 -->
    <el-dialog
      title="迁移任务详情"
      :visible.sync="detailDialogVisible"
      width="800px"
      class="detail-dialog"
    >
      <el-tabs v-model="activeDetailTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-form label-width="120px" class="detail-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="任务名称：">
                  <span>{{ currentTask.taskName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="迁移类型：">
                  <el-tag :type="currentTask.migrationType === 'FULL_SYSTEM' ? 'primary' : 'success'">
                    {{ currentTask.migrationType === 'FULL_SYSTEM' ? '全系统' : '部分目录' }}
                  </el-tag>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="源服务器：">
                  <span>{{ currentTask.sourceServerName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="目标服务器：">
                  <span>{{ currentTask.targetServerName }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="源路径：">
                  <span>{{ currentTask.sourcePath }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="目标路径：">
                  <span>{{ currentTask.targetPath }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="状态：">
                  <el-tag :type="getStatusTagType(currentTask.status)">
                    {{ getStatusText(currentTask.status) }}
                  </el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="进度：">
                  <el-progress
                    :percentage="currentTask.progress"
                    :status="getProgressStatus(currentTask.status)"
                    :stroke-width="12"
                    text-inside
                  ></el-progress>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="创建时间：">
              <span>{{ formatDateTime(currentTask.createdAt) }}</span>
            </el-form-item>
            
            <el-form-item label="开始时间：" v-if="currentTask.startTime">
              <span>{{ formatDateTime(currentTask.startTime) }}</span>
            </el-form-item>
            
            <el-form-item label="结束时间：" v-if="currentTask.endTime">
              <span>{{ formatDateTime(currentTask.endTime) }}</span>
            </el-form-item>
            
            <el-form-item label="错误信息：" v-if="currentTask.errorMessage">
              <el-alert
                :title="currentTask.errorMessage"
                type="error"
                show-icon
                :closable="false"
              >
              </el-alert>
            </el-form-item>
            
            <el-form-item label="描述：">
              <span>{{ currentTask.description }}</span>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="迁移步骤" name="steps">
          <MigrationStepDetail :task="currentTask" />
        </el-tab-pane>
      </el-tabs>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
        <el-button 
          type="primary" 
          @click="refreshTaskDetail" 
          :loading="refreshingDetail"
        >
          刷新
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import moment from 'moment'
import MigrationStepDetail from '@/components/MigrationStepDetail.vue'

export default {
  name: 'Migrations',
  components: {
    MigrationStepDetail
  },
  data() {
    return {
      dialogVisible: false,
      detailDialogVisible: false,
      pathSelectorVisible: false, // 路径选择对话框可见性
      isSelectingSource: true, // 标记正在选择源路径还是目标路径
      dialogTitle: '创建迁移任务',
      isEdit: false,
      loading: false,
      pathLoading: false,
      diskLoading: false,
      diskLoadError: '',
      currentTask: {},
      currentServer: null,
      currentPath: '',
      breadcrumbPaths: [],
      directoryList: [],
      filterForm: {
        taskName: '',
        status: '',
        migrationType: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 20  // 修改默认页面大小为20
      },
      taskForm: {
        id: null,
        taskName: '',
        migrationType: 'PARTIAL_DIRECTORY',
        sourceServerId: null,
        targetServerId: null,
        sourcePath: '',
        targetPath: '',
        description: ''
      },
      taskFormRules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        migrationType: [
          { required: true, message: '请选择迁移类型', trigger: 'change' }
        ],
        sourceServerId: [
          { required: true, message: '请选择源服务器', trigger: 'change' }
        ],
        targetServerId: [
          { required: true, message: '请选择目标服务器', trigger: 'change' }
        ],
        sourcePath: [
          { required: true, message: '请输入源路径', trigger: 'blur', validator: this.validateSourcePath }
        ],
        targetPath: [
          { required: true, message: '请输入目标路径', trigger: 'blur', validator: this.validateTargetPath }
        ]
      },
      // 磁盘相关数据
      diskList: [],
      selectedDisks: [],
    }
  },
  computed: {
    // 重新定义计算属性，避免与data中的属性冲突
    taskList() {
      return this.$store.state.migrations.tasks || []
    },
    serverList() {
      return this.$store.state.servers.servers || []
    },
    filteredTasks() {
      let result = this.taskList;
      
      // 应用过滤条件
      if (this.filterForm.taskName) {
        result = result.filter(task => 
          task.taskName && task.taskName.toLowerCase().includes(this.filterForm.taskName.toLowerCase())
        );
      }
      
      if (this.filterForm.status) {
        result = result.filter(task => task.status === this.filterForm.status);
      }
      
      if (this.filterForm.migrationType) {
        result = result.filter(task => task.migrationType === this.filterForm.migrationType);
      }
      
      return result;
    },
    paginatedTasks() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.filteredTasks.slice(start, end);
    }
  },
  async created() {
    await this.refreshTasks();
    await this.$store.dispatch('servers/fetchServers');
  },
  methods: {
    ...mapActions('migrations', ['fetchTasks', 'createTask', 'updateTask', 'deleteTask', 'executeTask']),
    ...mapActions('servers', ['getLinuxDiskInfo', 'getWindowsDiskInfo', 'getLinuxDirectoryStructure', 'getWindowsDirectoryStructure']),
    
    async refreshTasks() {
      this.loading = true;
      try {
        await this.fetchTasks();
      } catch (error) {
        this.$message.error('获取迁移任务失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    
    async refreshTaskDetail() {
      this.refreshingDetail = true;
      try {
        // 重新获取任务详情
        await this.refreshTasks();
        // 找到更新后的任务
        const updatedTask = this.taskList.find(task => task.id === this.currentTask.id);
        if (updatedTask) {
          this.currentTask = { ...updatedTask };
        }
        this.$message.success('刷新成功');
      } catch (error) {
        this.$message.error('刷新失败: ' + (error.message || '未知错误'));
      } finally {
        this.refreshingDetail = false;
      }
    },
    
    handleFilter() {
      this.pagination.currentPage = 1;
    },
    
    resetFilter() {
      this.filterForm = {
        taskName: '',
        status: '',
        migrationType: ''
      };
      this.pagination.currentPage = 1;
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    },
    
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待执行',
        'RUNNING': '运行中',
        'COMPLETED': '已完成',
        'FAILED': '失败',
        'PAUSED': '已暂停',
        'STOPPED': '已停止'
      };
      return statusMap[status] || status;
    },
    
    getStatusTagType(status) {
      const typeMap = {
        'PENDING': '',
        'RUNNING': 'warning',
        'COMPLETED': 'success',
        'FAILED': 'danger',
        'PAUSED': 'info',
        'STOPPED': 'danger'
      };
      return typeMap[status] || 'info';
    },
    
    getProgressStatus(status) {
      const statusMap = {
        'COMPLETED': 'success',
        'FAILED': 'exception'
      };
      return statusMap[status];
    },
    
    formatDateTime(date) {
      return date ? moment(date).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    
    validateSourcePath(rule, value, callback) {
      if (!value || value.trim() === '') {
        callback(new Error('请输入源路径'));
      } else if (value.trim().length < 1) {
        callback(new Error('源路径长度不能少于1个字符'));
      } else {
        callback();
      }
    },
    
    validateTargetPath(rule, value, callback) {
      if (!value || value.trim() === '') {
        callback(new Error('请输入目标路径'));
      } else if (value.trim().length < 1) {
        callback(new Error('目标路径长度不能少于1个字符'));
      } else {
        callback();
      }
    },
    
    showCreateDialog() {
      this.isEdit = false;
      this.dialogTitle = '创建迁移任务';
      this.taskForm = {
        id: null,
        taskName: '',
        migrationType: 'PARTIAL_DIRECTORY',
        sourceServerId: null,
        targetServerId: null,
        sourcePath: '',
        targetPath: '',
        description: ''
      };
      // 重置磁盘相关数据
      this.diskList = [];
      this.selectedDisks = [];
      this.diskLoadError = '';
      this.dialogVisible = true;
    },
    
    showDetails(task) {
      this.currentTask = { ...task };
      this.activeDetailTab = 'basic';
      this.detailDialogVisible = true;
    },
    
    handleSourceServerChange(serverId) {
      const server = this.serverList.find(s => s.id === serverId);
      if (server) {
        this.$set(this.taskForm, 'sourceServerName', server.name);
        // 当源服务器改变时，清空磁盘信息
        this.diskList = [];
        this.selectedDisks = [];
        this.diskLoadError = '';
        
        // 如果是全系统迁移，加载磁盘信息
        if (this.taskForm.migrationType === 'FULL_SYSTEM') {
          this.loadDiskInfo(server);
        }
      }
    },
    
    handleTargetServerChange(serverId) {
      const server = this.serverList.find(s => s.id === serverId);
      if (server) {
        this.$set(this.taskForm, 'targetServerName', server.name);
      }
    },
    
    handleMigrationTypeChange() {
      // 当迁移类型改变时，清除路径字段的验证错误
      this.$nextTick(() => {
        if (this.$refs.taskForm) {
          this.$refs.taskForm.clearValidate(['sourcePath', 'targetPath']);
        }
      });
      // 当迁移类型改变时，清空磁盘信息
      this.diskList = [];
      this.selectedDisks = [];
      this.diskLoadError = '';
      
      // 如果切换到全系统迁移且已选择源服务器，加载磁盘信息
      if (this.taskForm.migrationType === 'FULL_SYSTEM' && this.taskForm.sourceServerId) {
        const server = this.serverList.find(s => s.id === this.taskForm.sourceServerId);
        if (server) {
          this.loadDiskInfo(server);
        }
      }
    },
    
    async loadDiskInfo(server) {
      this.diskLoading = true;
      this.diskLoadError = '';
      
      try {
        let result;
        if (server.osType === 'LINUX') {
          result = await this.getLinuxDiskInfo(server.id);
        } else if (server.osType === 'WINDOWS') {
          result = await this.getWindowsDiskInfo(server.id);
        } else {
          throw new Error('不支持的操作系统类型');
        }
        
        if (result.success) {
          // 解析磁盘信息
          if (server.osType === 'LINUX') {
            // 解析Linux磁盘信息 (JSON格式)
            try {
              const diskData = JSON.parse(result.output);
              this.diskList = diskData.blockdevices
                .filter(device => device.type === 'disk')
                .map(device => ({
                  name: device.name,
                  size: device.size,
                  type: device.type
                }));
            } catch (parseError) {
              console.error('解析Linux磁盘信息失败:', parseError);
              this.diskLoadError = '解析磁盘信息失败: ' + parseError.message;
            }
          } else {
            // 解析Windows磁盘信息 (JSON格式)
            try {
              const diskData = JSON.parse(result.output);
              if (Array.isArray(diskData)) {
                this.diskList = diskData.map(disk => ({
                  name: disk.DeviceID,
                  size: this.formatBytes(disk.Size),
                  freeSpace: this.formatBytes(disk.FreeSpace)
                }));
              } else {
                this.diskList = [{
                  name: diskData.DeviceID,
                  size: this.formatBytes(diskData.Size),
                  freeSpace: this.formatBytes(diskData.FreeSpace)
                }];
              }
            } catch (parseError) {
              console.error('解析Windows磁盘信息失败:', parseError);
              this.diskLoadError = '解析磁盘信息失败: ' + parseError.message;
            }
          }
        } else {
          this.diskLoadError = '获取磁盘信息失败: ' + result.message;
        }
      } catch (error) {
        console.error('加载磁盘信息失败:', error);
        this.diskLoadError = '加载磁盘信息失败: ' + (error.message || '未知错误');
      } finally {
        this.diskLoading = false;
      }
    },
    
    formatBytes(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    handleDialogClose(done) {
      this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => {
        // 取消关闭
      });
    },
    
    async handleSave() {
      this.$refs.taskForm.validate(async (valid) => {
        if (valid) {
          try {
            // 获取源服务器和目标服务器信息
            const sourceServer = this.serverList.find(s => s.id === this.taskForm.sourceServerId);
            const targetServer = this.serverList.find(s => s.id === this.taskForm.targetServerId);
            
            if (!sourceServer || !targetServer) {
              this.$message.error('源服务器或目标服务器不存在');
              return;
            }
            
            // 准备任务数据
            const taskData = {
              ...this.taskForm,
              sourceServerName: sourceServer ? sourceServer.name : '',
              targetServerName: targetServer ? targetServer.name : ''
            };
            
            // 如果是全系统迁移且选择了磁盘，将选择的磁盘信息保存到任务中
            if (this.taskForm.migrationType === 'FULL_SYSTEM' && this.selectedDisks.length > 0) {
              taskData.selectedDisks = JSON.stringify(this.selectedDisks);
            }
            
            await this.createTask(taskData);
            this.$message.success('迁移任务创建成功');
            await this.refreshTasks();
            this.dialogVisible = false;
          } catch (error) {
            this.$message.error(error.message || '操作失败');
          }
        }
      });
    },
    
    async executeTask(task) {
      // 验证任务状态，只有待执行的任务才能执行
      if (task.status !== 'PENDING' && task.status !== 'FAILED') {
        this.$message.warning('只有待执行或失败的任务才能启动');
        return;
      }
      
      // 验证源服务器和目标服务器是否存在
      if (!task.sourceServerId || !task.targetServerId) {
        this.$message.warning('源服务器或目标服务器信息不完整');
        return;
      }
      
      try {
        // 显示执行确认对话框
        await this.$confirm('确定要执行此迁移任务吗？执行过程中请勿关闭页面。', '执行确认', {
          confirmButtonText: '确定执行',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 显示执行中提示
        const loading = this.$loading({
          lock: true,
          text: '正在启动迁移任务...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        try {
          // 确保只执行当前任务
          await this.$store.dispatch('migrations/executeTask', task.id);
          this.$message.success('迁移任务已启动');
          // 刷新任务列表
          await this.refreshTasks();
        } finally {
          loading.close();
        }
      } catch (error) {
        if (error === 'cancel' || error === 'close') {
          // 用户取消操作
          this.$message.info('已取消执行');
        } else {
          this.$message.error(error.message || '执行失败');
        }
      }
    },
    
    async handleDelete(task) {
      this.$confirm('此操作将永久删除该迁移任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 确保只删除当前任务
          await this.$store.dispatch('migrations/deleteTask', task.id);
          this.$message.success('删除成功');
          await this.refreshTasks();
        } catch (error) {
          this.$message.error(error.message || '删除失败');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    async reExecuteTask(task) {
      // 验证任务状态，只有已完成或失败的任务才能再次执行
      if (task.status !== 'COMPLETED' && task.status !== 'FAILED') {
        this.$message.warning('只有已完成或失败的任务才能再次执行');
        return;
      }
      
      // 验证源服务器和目标服务器是否存在
      if (!task.sourceServerId || !task.targetServerId) {
        this.$message.warning('源服务器或目标服务器信息不完整');
        return;
      }
      
      try {
        // 显示再次执行确认对话框
        await this.$confirm('确定要再次执行此迁移任务吗？这将重新开始整个迁移过程。', '再次执行确认', {
          confirmButtonText: '确定执行',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 显示执行中提示
        const loading = this.$loading({
          lock: true,
          text: '正在启动迁移任务...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        try {
          // 重置任务状态为PENDING，然后执行任务
          await this.$store.dispatch('migrations/updateTaskStatus', { 
            id: task.id, 
            status: 'PENDING', 
            progress: 0,
            errorMessage: null
          });
          
          // 刷新任务列表以显示状态更新
          await this.refreshTasks();
          
          // 执行任务
          await this.$store.dispatch('migrations/executeTask', task.id);
          this.$message.success('迁移任务已启动');
          
          // 刷新任务列表
          await this.refreshTasks();
        } finally {
          loading.close();
        }
      } catch (error) {
        if (error === 'cancel' || error === 'close') {
          // 用户取消操作
          this.$message.info('已取消执行');
        } else {
          this.$message.error(error.message || '执行失败');
        }
      }
    },
    
    async pauseTask(task) {
      // 验证任务状态，只有运行中的任务才能暂停
      if (task.status !== 'RUNNING') {
        this.$message.warning('只有运行中的任务才能暂停');
        return;
      }
      
      try {
        // 显示暂停确认对话框
        await this.$confirm('确定要暂停此迁移任务吗？', '暂停确认', {
          confirmButtonText: '确定暂停',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 显示暂停中提示
        const loading = this.$loading({
          lock: true,
          text: '正在暂停迁移任务...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        try {
          // 暂停任务
          await this.$store.dispatch('migrations/pauseTask', task.id);
          this.$message.success('迁移任务已暂停');
          
          // 刷新任务列表
          await this.refreshTasks();
        } finally {
          loading.close();
        }
      } catch (error) {
        if (error === 'cancel' || error === 'close') {
          // 用户取消操作
          this.$message.info('已取消暂停');
        } else {
          this.$message.error(error.message || '暂停失败');
        }
      }
    },
    
    async resumeTask(task) {
      // 验证任务状态，只有暂停的任务才能恢复
      if (task.status !== 'PAUSED') {
        this.$message.warning('只有暂停的任务才能恢复');
        return;
      }
      
      try {
        // 显示恢复确认对话框
        await this.$confirm('确定要恢复此迁移任务吗？', '恢复确认', {
          confirmButtonText: '确定恢复',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 显示恢复中提示
        const loading = this.$loading({
          lock: true,
          text: '正在恢复迁移任务...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        try {
          // 恢复任务
          await this.$store.dispatch('migrations/resumeTask', task.id);
          this.$message.success('迁移任务已恢复');
          
          // 刷新任务列表
          await this.refreshTasks();
        } finally {
          loading.close();
        }
      } catch (error) {
        if (error === 'cancel' || error === 'close') {
          // 用户取消操作
          this.$message.info('已取消恢复');
        } else {
          this.$message.error(error.message || '恢复失败');
        }
      }
    },
    
    async stopTask(task) {
      // 验证任务状态，只有运行中或暂停的任务才能停止
      if (task.status !== 'RUNNING' && task.status !== 'PAUSED') {
        this.$message.warning('只有运行中或暂停的任务才能停止');
        return;
      }
      
      try {
        // 显示停止确认对话框
        await this.$confirm('确定要停止此迁移任务吗？停止后任务将无法恢复。', '停止确认', {
          confirmButtonText: '确定停止',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 显示停止中提示
        const loading = this.$loading({
          lock: true,
          text: '正在停止迁移任务...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        try {
          // 停止任务
          await this.$store.dispatch('migrations/stopTask', task.id);
          this.$message.success('迁移任务已停止');
          
          // 刷新任务列表
          await this.refreshTasks();
        } finally {
          loading.close();
        }
      } catch (error) {
        if (error === 'cancel' || error === 'close') {
          // 用户取消操作
          this.$message.info('已取消停止');
        } else {
          this.$message.error(error.message || '停止失败');
        }
      }
    },
    
    // 显示源路径选择器
    async showSourcePathSelector() {
      if (!this.taskForm.sourceServerId) {
        this.$message.warning('请先选择源服务器');
        return;
      }
      
      const server = this.serverList.find(s => s.id === this.taskForm.sourceServerId);
      if (!server) {
        this.$message.error('未找到源服务器信息');
        return;
      }
      
      this.currentServer = server;
      this.currentPath = server.osType === 'WINDOWS' ? 'C:\\' : '/';
      this.breadcrumbPaths = [{ name: '根目录', path: this.currentPath }];
      
      await this.loadDirectoryStructure(server, this.currentPath);
      this.pathSelectorVisible = true;
      this.isSelectingSource = true; // 标记正在选择源路径
    },
    
    // 显示目标路径选择器
    async showTargetPathSelector() {
      if (!this.taskForm.targetServerId) {
        this.$message.warning('请先选择目标服务器');
        return;
      }
      
      const server = this.serverList.find(s => s.id === this.taskForm.targetServerId);
      if (!server) {
        this.$message.error('未找到目标服务器信息');
        return;
      }
      
      this.currentServer = server;
      this.currentPath = server.osType === 'WINDOWS' ? 'C:\\' : '/';
      this.breadcrumbPaths = [{ name: '根目录', path: this.currentPath }];
      
      await this.loadDirectoryStructure(server, this.currentPath);
      this.pathSelectorVisible = true;
      this.isSelectingSource = false; // 标记正在选择目标路径
    },
    
    // 加载目录结构
    async loadDirectoryStructure(server, path) {
      this.pathLoading = true;
      try {
        let result;
        if (server.osType === 'LINUX') {
          result = await this.getLinuxDirectoryStructure({ serverId: server.id, path });
        } else if (server.osType === 'WINDOWS') {
          result = await this.getWindowsDirectoryStructure({ serverId: server.id, path });
        } else {
          throw new Error('不支持的操作系统类型');
        }
        
        if (result.success) {
          if (server.osType === 'LINUX') {
            // 解析Linux目录结构
            const lines = result.output.split('\n').filter(line => line.trim() !== '');
            this.directoryList = lines.map(line => {
              const name = line.split('/').pop() || line;
              return {
                name: name,
                path: line
              };
            });
          } else {
            // 解析Windows目录结构
            try {
              const dirData = JSON.parse(result.output);
              if (Array.isArray(dirData)) {
                this.directoryList = dirData.map(item => ({
                  name: item.Name || item.FullName.split('\\').pop(),
                  path: item.FullName || item.Path
                }));
              } else {
                this.directoryList = [{
                  name: dirData.Name || dirData.FullName.split('\\').pop(),
                  path: dirData.FullName || dirData.Path
                }];
              }
            } catch (parseError) {
              // 如果解析失败，按行处理
              const lines = result.output.split('\n').filter(line => line.trim() !== '');
              this.directoryList = lines.map(line => {
                const name = line.split('\\').pop() || line;
                return {
                  name: name,
                  path: line
                };
              });
            }
          }
        } else {
          this.$message.error('获取目录结构失败: ' + result.message);
          this.directoryList = [];
        }
      } catch (error) {
        this.$message.error('加载目录结构失败: ' + (error.message || '未知错误'));
        this.directoryList = [];
      } finally {
        this.pathLoading = false;
      }
    },
    
    // 处理目录点击
    async handleDirectoryClick(row) {
      this.currentPath = row.path;
      // 更新面包屑
      const pathParts = this.currentPath.split(this.currentServer.osType === 'WINDOWS' ? '\\' : '/');
      this.breadcrumbPaths = pathParts
        .filter(part => part !== '')
        .map((part, index) => {
          const path = pathParts.slice(0, index + 1).join(this.currentServer.osType === 'WINDOWS' ? '\\' : '/');
          return {
            name: part,
            path: this.currentServer.osType === 'WINDOWS' ? path + '\\' : '/' + path
          };
        });
      
      // 如果是Windows系统且路径不以\结尾，添加\
      if (this.currentServer.osType === 'WINDOWS' && !this.currentPath.endsWith('\\')) {
        this.currentPath += '\\';
      }
      
      await this.loadDirectoryStructure(this.currentServer, this.currentPath);
    },
    
    // 导航到指定路径
    async navigateToPath(path) {
      this.currentPath = path;
      await this.loadDirectoryStructure(this.currentServer, this.currentPath);
      
      // 更新面包屑
      const pathParts = path.split(this.currentServer.osType === 'WINDOWS' ? '\\' : '/');
      this.breadcrumbPaths = pathParts
        .filter(part => part !== '')
        .map((part, index) => {
          const subPath = pathParts.slice(0, index + 1).join(this.currentServer.osType === 'WINDOWS' ? '\\' : '/');
          return {
            name: part,
            path: this.currentServer.osType === 'WINDOWS' ? subPath + (subPath.endsWith('\\') ? '' : '\\') : '/' + subPath
          };
        });
    },
    
    // 确认路径选择
    confirmPathSelection() {
      if (this.isSelectingSource) {
        // 选择的是源路径
        this.taskForm.sourcePath = this.currentPath;
      } else {
        // 选择的是目标路径
        this.taskForm.targetPath = this.currentPath;
      }
      this.pathSelectorVisible = false;
    }
  }
}
</script>

<style scoped>
.migrations-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.task-count {
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.filter-content {
  padding: 20px 0;
}

.filter-form ::v-deep .el-form-item {
  margin-bottom: 0;
}

.migrations-table {
  margin-bottom: 20px;
}

.migrations-table ::v-deep .el-table__row:hover {
  background-color: #f5f7fa;
}

.progress-text {
  font-size: 12px;
  color: #606266;
  text-align: center;
  margin-top: 3px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.migration-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.migration-form ::v-deep .el-form-item {
  margin-bottom: 20px;
}

.detail-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.detail-form ::v-deep .el-form-item {
  margin-bottom: 15px;
}

.detail-form ::v-deep .el-form-item__label {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-left {
    justify-content: center;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .filter-content {
    padding: 15px 0;
  }
  
  .filter-form ::v-deep .el-form-item {
    margin-bottom: 15px;
    width: 100%;
  }
  
  .filter-form ::v-deep .el-form-item__content {
    width: 100%;
  }
  
  .filter-form ::v-deep .el-input,
  .filter-form ::v-deep .el-select {
    width: 100% !important;
  }
}
</style>